﻿using Abp;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using AutoMapper.QueryableExtensions;
using FwProject.Com.Dto;
using FwProject.ShopApplication;
using FwProject.ShoppingMall.Com;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;

namespace FwProject.Com
{
    public  class ContentTypeAppService: FwProjectAppServiceBase, IContentTypeAppService
    {
        private readonly IRepository<ContentType, Guid> _contentTypeRepository;
        public IGuidGenerator _guid { get; set; }
        public ContentTypeAppService(IRepository<ContentType, Guid> contentTypeRepository)
        {
            _contentTypeRepository = contentTypeRepository;
            _guid = SequentialGuidGenerator.Instance;
        }
        public async Task<LayerDataBaseDto> GetLayerDataAsync(int page, int limit, string keyword)
        {
            var query = _contentTypeRepository.GetAll();
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(o => o.Name.Contains(keyword));

            var pagelist = await query.OrderByDescending(o => o.Id).ProjectTo<ContentTypeOutputDto>().ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }

        public async Task<ContentTypeOutputDto> GetEntityByIdAsync(Guid id)
        {
            var entity = await _contentTypeRepository.GetAsync(id);
            return entity.MapTo<ContentTypeOutputDto>();
        }

        public async Task<List<ContentTypeOutputDto>> GetListAsync()
        {
            var list = await _contentTypeRepository.GetAll().ToListAsync();
            return list.MapTo<List<ContentTypeOutputDto>>();
        }

        public async Task<Guid> CreateAsync(ContentTypeEnterDto input)
        {
            var entity = input.MapTo<ContentType>();
            entity.Id = _guid.Create();
            return await _contentTypeRepository.InsertAndGetIdAsync(entity); 
        }

        public async Task ModifyAsync(Guid id, ContentTypeEnterDto input)
        {
            var entity = await _contentTypeRepository.GetAsync(id);
            input.MapTo(entity);
            await _contentTypeRepository.UpdateAsync(entity);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _contentTypeRepository.DeleteAsync(id);
        }
    }
}
